// SmartInput 浏览器扩展弹窗脚本

let isConnected = false;
let isPairing = false;
let pairedDevices = [];
let isAutoInsertEnabled = true;

// DOM元素
const connectionStatus = document.getElementById('connectionStatus');
const deviceId = document.getElementById('deviceId');
const pairedCount = document.getElementById('pairedCount');
const serverUrl = document.getElementById('serverUrl');
const qrContainer = document.getElementById('qrContainer');
const qrCode = document.getElementById('qrCode');
const pairingCode = document.getElementById('pairingCode');
const deviceList = document.getElementById('deviceList');
const devices = document.getElementById('devices');
const pairBtn = document.getElementById('pairBtn');
const pairBtnText = document.getElementById('pairBtnText');
const pairBtnLoading = document.getElementById('pairBtnLoading');
const reconnectBtn = document.getElementById('reconnectBtn');

// 初始化
document.addEventListener('DOMContentLoaded', () => {
  loadStatus();
  setupEventListeners();
  setupAutoInsertControl();
});

// 设置自动录入控制
function setupAutoInsertControl() {
  // 创建自动录入控制区域
  const autoInsertSection = document.createElement('div');
  autoInsertSection.className = 'auto-insert-section';
  autoInsertSection.innerHTML = `
    <div class="section-title">
      <span class="icon">🎤</span>
      自动录入设置
    </div>
    <div class="auto-insert-control">
      <label class="toggle-label">
        <input type="checkbox" id="autoInsertToggle" ${isAutoInsertEnabled ? 'checked' : ''}>
        <span class="toggle-slider"></span>
        <span class="toggle-text">自动录入语音文字</span>
      </label>
      <div class="auto-insert-help">
        启用后，语音文字将自动录入到当前页面的输入框中
      </div>
    </div>
    <div class="current-input-info" id="currentInputInfo" style="display: none;">
      <div class="info-item">
        <span class="info-label">当前输入框:</span>
        <span class="info-value" id="currentInputElement">-</span>
      </div>
    </div>
  `;

  // 插入到配对按钮之前
  const pairSection = document.querySelector('.pair-section');
  if (pairSection) {
    pairSection.parentNode.insertBefore(autoInsertSection, pairSection);
  }

  // 设置切换事件
  const autoInsertToggle = document.getElementById('autoInsertToggle');
  autoInsertToggle.addEventListener('change', handleAutoInsertToggle);
}

// 处理自动录入切换
async function handleAutoInsertToggle(event) {
  const enabled = event.target.checked;
  isAutoInsertEnabled = enabled;
  
  try {
    // 通知background脚本
    await chrome.runtime.sendMessage({
      type: 'TOGGLE_AUTO_INSERT',
      enabled: enabled
    });
    
    // 通知当前标签页
    const tabs = await chrome.tabs.query({ active: true, currentWindow: true });
    if (tabs[0]) {
      await chrome.tabs.sendMessage(tabs[0].id, {
        type: 'TOGGLE_AUTO_INSERT',
        enabled: enabled
      });
    }
    
    showNotification(
      enabled ? '自动录入已启用' : '自动录入已禁用',
      enabled ? '语音文字将自动录入到输入框' : '需要手动点击输入框后录入',
      enabled ? 'success' : 'warning'
    );
    
  } catch (error) {
    console.error('切换自动录入失败:', error);
    // 恢复复选框状态
    event.target.checked = !enabled;
    isAutoInsertEnabled = !enabled;
  }
}

// 更新当前输入框信息
async function updateCurrentInputInfo() {
  try {
    const tabs = await chrome.tabs.query({ active: true, currentWindow: true });
    if (tabs[0]) {
      const response = await chrome.tabs.sendMessage(tabs[0].id, {
        type: 'GET_STATUS'
      });
      
      if (response && response.success) {
        const currentInputInfo = document.getElementById('currentInputInfo');
        const currentInputElement = document.getElementById('currentInputElement');
        
        if (response.currentInput) {
          currentInputElement.textContent = response.currentInput;
          currentInputInfo.style.display = 'block';
        } else {
          currentInputInfo.style.display = 'none';
        }
      }
    }
  } catch (error) {
    // 忽略错误，可能页面没有内容脚本
  }
}

// 设置事件监听器
function setupEventListeners() {
  pairBtn.addEventListener('click', handlePairClick);
  reconnectBtn.addEventListener('click', handleReconnectClick);
  
  // 添加同步按钮事件监听
  const syncBtn = document.getElementById('syncBtn');
  if (syncBtn) {
    syncBtn.addEventListener('click', handleSyncClick);
  }
  
  // 监听来自background的消息
  chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
    switch (message.type) {
      case 'CONNECTION_STATUS':
        updateConnectionStatus(message.connected);
        updateServerUrl(message.serverUrl);
        break;
        
      case 'DEVICE_PAIRED':
        handleDevicePaired(message.device);
        break;
        
      case 'PAIRING_CODE':
        showPairingCode(message.code, message.qrCode);
        break;

      case 'PAIRING_FAILED':
        handlePairingFailed(message.error);
        break;
        
      case 'PAIRING_STATUS_SYNCED':
        updatePairedDevices(message.pairedDevices);
        break;
    }
  });
}

// 加载状态
async function loadStatus() {
  try {
    const response = await chrome.runtime.sendMessage({ type: 'GET_STATUS' });
    
    if (response) {
      updateConnectionStatus(response.connected);
      updateDeviceId(response.deviceId);
      updatePairedDevices(response.pairedDevices || []);
      updateServerUrl(response.currentServer);
      
      // 更新自动录入状态
      if (response.autoInsert !== undefined) {
        isAutoInsertEnabled = response.autoInsert;
        const autoInsertToggle = document.getElementById('autoInsertToggle');
        if (autoInsertToggle) {
          autoInsertToggle.checked = isAutoInsertEnabled;
        }
      }
    }
    
    // 更新当前输入框信息
    await updateCurrentInputInfo();
  } catch (error) {
    console.error('加载状态失败:', error);
  }
}

// 更新连接状态
function updateConnectionStatus(connected) {
  isConnected = connected;

  if (connected) {
    connectionStatus.textContent = '已连接';
    connectionStatus.className = 'status-value status-connected';
    pairBtn.disabled = false;
    hideConnectionHelp();
  } else {
    connectionStatus.textContent = '未连接';
    connectionStatus.className = 'status-value status-disconnected';
    pairBtn.disabled = true;
    hidePairingCode();
    showConnectionHelp();
  }
}

// 显示连接帮助
function showConnectionHelp() {
  // 检查是否已经存在帮助元素
  let helpElement = document.getElementById('connectionHelp');
  if (!helpElement) {
    helpElement = document.createElement('div');
    helpElement.id = 'connectionHelp';
    helpElement.className = 'connection-help';
    helpElement.innerHTML = `
      <div class="help-content">
        <div class="help-icon">🔒</div>
        <div class="help-text">
          <strong>连接失败？</strong><br>
          可能需要接受HTTPS证书
        </div>
        <button class="help-button" onclick="openCertificateGuide()">
          📋 查看解决方案
        </button>
      </div>
    `;

    // 插入到连接状态后面
    const statusSection = document.querySelector('.status-section');
    if (statusSection) {
      statusSection.appendChild(helpElement);
    }
  }
  helpElement.style.display = 'block';
}

// 隐藏连接帮助
function hideConnectionHelp() {
  const helpElement = document.getElementById('connectionHelp');
  if (helpElement) {
    helpElement.style.display = 'none';
  }
}

// 打开证书指导页面
function openCertificateGuide() {
  chrome.tabs.create({
    url: chrome.runtime.getURL('certificate-guide.html')
  });
}

// 更新设备ID
function updateDeviceId(id) {
  if (id) {
    // 显示完整的设备ID，但用小字体
    deviceId.textContent = id;
    deviceId.title = '点击复制设备ID';
    deviceId.style.cursor = 'pointer';
    deviceId.style.fontSize = '11px';
    deviceId.style.fontFamily = 'monospace';
    deviceId.style.wordBreak = 'break-all';
    
    // 添加点击复制功能
    deviceId.onclick = () => {
      navigator.clipboard.writeText(id).then(() => {
        const originalText = deviceId.textContent;
        deviceId.textContent = '已复制!';
        setTimeout(() => {
          deviceId.textContent = originalText;
        }, 1000);
      }).catch(() => {
        // 降级方案：选中文本
        const range = document.createRange();
        range.selectNode(deviceId);
        window.getSelection().removeAllRanges();
        window.getSelection().addRange(range);
      });
    };
  } else {
    deviceId.textContent = '-';
    deviceId.title = '';
    deviceId.style.cursor = 'default';
    deviceId.onclick = null;
  }
}

// 更新服务器地址
function updateServerUrl(url) {
  if (url) {
    serverUrl.textContent = url.replace('http://', '').replace('ws://', '');
  } else {
    serverUrl.textContent = '-';
  }
}

// 更新配对设备列表
function updatePairedDevices(devices) {
  pairedDevices = devices || [];
  pairedCount.textContent = pairedDevices.length;
  
  console.log('📱 更新配对设备显示:', pairedDevices);
  
  if (pairedDevices.length > 0) {
    showDeviceList(pairedDevices);
  } else {
    hideDeviceList();
  }
}

// 显示设备列表
function showDeviceList(devices) {
  const devicesContainer = document.getElementById('devices');
  devicesContainer.innerHTML = '';
  
  devices.forEach((deviceId, index) => {
    const deviceItem = document.createElement('div');
    deviceItem.className = 'device-item';
    
    // 根据设备ID判断设备类型
    let deviceType = '📱';
    let deviceName = '移动设备';
    
    if (deviceId.includes('mobile') || deviceId.includes('phone') || deviceId.includes('android')) {
      deviceType = '📱';
      deviceName = '移动设备';
    } else if (deviceId.includes('browser') || deviceId.includes('chrome')) {
      deviceType = '🌐';
      deviceName = '浏览器';
    } else if (deviceId.includes('desktop')) {
      deviceType = '💻';
      deviceName = '桌面设备';
    }
    
    // 生成更友好的显示名称
    let displayName = deviceName;
    if (deviceId.includes('android')) {
      displayName = 'Android 设备';
    } else if (deviceId.includes('ios') || deviceId.includes('iphone')) {
      displayName = 'iOS 设备';
    }
    
    // 显示完整的设备ID，但限制长度避免过长
    const displayId = deviceId.length > 20 ? deviceId.substring(0, 20) + '...' : deviceId;
    
    deviceItem.innerHTML = `
      <div class="device-icon">${deviceType}</div>
      <div class="device-info">
        <div class="device-name">${displayName} ${index + 1}</div>
        <div class="device-status" title="${deviceId}">${displayId}</div>
      </div>
    `;
    devicesContainer.appendChild(deviceItem);
  });
  
  deviceList.classList.remove('hidden');
}

// 隐藏设备列表
function hideDeviceList() {
  deviceList.classList.add('hidden');
}

// 处理配对按钮点击
async function handlePairClick() {
  if (isPairing) {
    // 停止配对
    stopPairing();
  } else {
    // 开始配对
    startPairing();
  }
}

// 开始配对
async function startPairing() {
  try {
    isPairing = true;
    updatePairButton();
    
    const response = await chrome.runtime.sendMessage({ type: 'START_PAIRING' });
    
    if (!response.success) {
      throw new Error('启动配对失败');
    }
    
  } catch (error) {
    console.error('配对失败:', error);
    stopPairing();
    alert('配对失败: ' + error.message);
  }
}

// 停止配对
function stopPairing() {
  isPairing = false;
  updatePairButton();
  hidePairingCode();
}

// 更新配对按钮状态
function updatePairButton() {
  if (isPairing) {
    pairBtnText.textContent = '停止配对';
    pairBtnLoading.classList.remove('hidden');
    pairBtn.className = 'btn btn-secondary';
  } else {
    pairBtnText.textContent = '开始配对';
    pairBtnLoading.classList.add('hidden');
    pairBtn.className = 'btn btn-primary';
  }
}

// 显示配对码
function showPairingCode(code, qrCodeData) {
  pairingCode.textContent = code;
  
  // 显示QR码
  if (qrCodeData) {
    qrCode.innerHTML = `<img src="${qrCodeData}" alt="配对二维码" class="qr-code">`;
  }
  
  qrContainer.style.display = 'block';
  
  // 5分钟后自动隐藏
  setTimeout(() => {
    if (isPairing) {
      stopPairing();
    }
  }, 300000);
}

// 隐藏配对码
function hidePairingCode() {
  qrContainer.style.display = 'none';
  qrCode.innerHTML = '';
  pairingCode.textContent = '-';
}

// 处理设备配对成功
function handleDevicePaired(device) {
  console.log('设备配对成功:', device);
  
  // 停止配对
  stopPairing();
  
  // 获取设备ID，支持多种字段名
  const deviceId = device.deviceId || device.mobileDeviceId;
  const deviceName = device.deviceName || '移动设备';
  
  if (deviceId && !pairedDevices.includes(deviceId)) {
    pairedDevices.push(deviceId);
    updatePairedDevices(pairedDevices);
  }
  
  // 显示成功提示
  showNotification(`设备配对成功！已连接到 ${deviceName}`, 'success');
}

// 处理重连按钮点击
async function handleReconnectClick() {
  try {
    reconnectBtn.disabled = true;
    reconnectBtn.textContent = '连接中...';
    
    await chrome.runtime.sendMessage({ type: 'RECONNECT' });
    
    // 等待一下再重新加载状态
    setTimeout(() => {
      loadStatus();
      reconnectBtn.disabled = false;
      reconnectBtn.textContent = '重新连接';
    }, 2000);
    
  } catch (error) {
    console.error('重连失败:', error);
    reconnectBtn.disabled = false;
    reconnectBtn.textContent = '重新连接';
  }
}

// 处理同步配对状态按钮点击
async function handleSyncClick() {
  try {
    const syncBtn = document.getElementById('syncBtn');
    if (syncBtn) {
      syncBtn.disabled = true;
      syncBtn.textContent = '同步中...';
    }
    
    await chrome.runtime.sendMessage({ type: 'SYNC_PAIRING_STATUS' });
    
    // 等待一下再重新加载状态
    setTimeout(() => {
      loadStatus();
      if (syncBtn) {
        syncBtn.disabled = false;
        syncBtn.textContent = '同步状态';
      }
    }, 1000);
    
  } catch (error) {
    console.error('同步失败:', error);
    const syncBtn = document.getElementById('syncBtn');
    if (syncBtn) {
      syncBtn.disabled = false;
      syncBtn.textContent = '同步状态';
    }
  }
}

// 显示通知
function showNotification(message, type = 'info') {
  // 创建通知元素
  const notification = document.createElement('div');
  notification.style.cssText = `
    position: fixed;
    top: 10px;
    right: 10px;
    background: ${type === 'success' ? '#4CAF50' : '#2196F3'};
    color: white;
    padding: 12px 16px;
    border-radius: 4px;
    font-size: 14px;
    z-index: 10000;
    animation: slideIn 0.3s ease-out;
  `;
  notification.textContent = message;
  
  document.body.appendChild(notification);
  
  // 3秒后移除
  setTimeout(() => {
    if (notification.parentNode) {
      notification.style.animation = 'slideOut 0.3s ease-out';
      setTimeout(() => {
        if (notification.parentNode) {
          notification.parentNode.removeChild(notification);
        }
      }, 300);
    }
  }, 3000);
}

// 添加样式
const style = document.createElement('style');
style.textContent = `
  @keyframes slideIn {
    from { transform: translateX(100%); opacity: 0; }
    to { transform: translateX(0); opacity: 1; }
  }
  
  @keyframes slideOut {
    from { transform: translateX(0); opacity: 1; }
    to { transform: translateX(100%); opacity: 0; }
  }
`;
document.head.appendChild(style);

// 处理配对失败
function handlePairingFailed(error) {
  console.error('配对失败:', error);

  // 停止配对状态
  stopPairing();

  // 显示错误通知
  showNotification(`配对失败: ${error || '未知错误'}`, 'error');
}
